package com.njdj.gps.record.task;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.njdj.gps.common.constants.NjdjConstants;
import com.njdj.gps.common.util.Utils;
import com.njdj.gps.kernel.entity.GpsCarHis;
import com.njdj.gps.kernel.entity.SeDevice;
import com.njdj.gps.kernel.entity.SeTask;
import com.njdj.gps.kernel.service.ICreateIdService;
import com.njdj.gps.kernel.service.IGpsCarHisService;
import com.njdj.gps.kernel.service.ISeDeviceService;
import com.njdj.gps.kernel.service.ISeTaskService;
import com.njdj.gps.record.QueryCarHistory;

public class SaveCarHistory {
	@Autowired
	ICreateIdService createIdService;
	@Autowired
	IGpsCarHisService gpsCarHisService;
	@Autowired
	ISeDeviceService seDeviceService;
	@Autowired
	ISeTaskService seTaskService;
	
	//检查帐号
	public void checkAccounts(){
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("status", 0);
		List<SeDevice> deviceList = seDeviceService.listModel(param);
		for(SeDevice seDevice: deviceList){
			if(null != seDevice && null != seDevice.getCarid() && !"".equals(seDevice.getCarid()) && null != seDevice.getPassward() && !"".equals(seDevice.getPassward()) && null != seDevice.getUsername() && !"".equals(seDevice.getUsername()) ){
				String carid = seDevice.getCarid();
				String password = seDevice.getPassward();
				String username = seDevice.getUsername();
				doCarHistoryTask(carid, username, password);
			}
		}
	}
	
	//执行检索请求
	public void doCarHistoryTask(String carid, String username, String passward){
		
		List<Map<String, Object>> tasks = listTasks(carid);
		if(null == tasks || tasks.size() == 0){
			System.out.println("无任务");
			return;
		}
		
		for(Map<String, Object> task : tasks){
			if(null == task || null == task.get("querytime") || "".equals(task.get("querytime")) || null == task.get("stime") || "".equals(task.get("stime")) || null == task.get("etime") || "".equals(task.get("etime"))){
				continue;
			}
			
			//任务实体
			Long id = createIdService.getId();
			SeTask seTask = new SeTask();
			seTask.setId(id);
			seTask.setCarid(carid);
			try{
				String querytime = task.get("querytime").toString();
				SimpleDateFormat format = new SimpleDateFormat("yyyy-M-dd");
				seTask.setQuerytime(format.parse(querytime));
			} catch(ParseException e) {
            	System.out.println("转换日期对象失败");
            }
			seTask.setParams("carId=" + carid + " sTime=" + task.get("stime") + " eTime=" + task.get("etime"));
			
			Date requestTime = new Date();
			//查询任务
			QueryCarHistory carHistory = new QueryCarHistory();
			
			carHistory.setCarId(carid);
			carHistory.setSTime(task.get("stime").toString());
			carHistory.setETime(task.get("etime").toString());
			List<GpsCarHis> gpsCarHisList = carHistory.query(carid, username, passward);
			if(null != gpsCarHisList && gpsCarHisList.size() > 0){
				seTask.setResultcount((long)gpsCarHisList.size());
				seTask.setCreatetime(new Date());
				seTask.setCosttime(seTask.getCreatetime().getTime() - requestTime.getTime());  //查询所消耗的时间
				//结果插入数据库
				gpsCarHisService.saveQueryCarHis(seTask, gpsCarHisList);
			} else {
				seTask.setResultcount(0L);
				seTask.setCreatetime(new Date());
				seTask.setCosttime(seTask.getCreatetime().getTime() - requestTime.getTime());  //查询所消耗的时间
				//结果插入数据库
				gpsCarHisService.saveQueryCarHis(seTask, null);
			}
		}
		System.out.println("finish today's tasks");
	}
	
	//获取需要执行的任务
	private List<Map<String, Object>> listTasks(String carid) {
		List<Map<String, Object>> tasks = new ArrayList<Map<String,Object>>();
		Map<String, Object> param = new HashMap<String, Object>();
		
		DateFormat formats = new java.text.SimpleDateFormat("yyyy-MM-dd");
		DateFormat formatd = new java.text.SimpleDateFormat("yyyy-MM-dd");
		
		param.put("carid", carid);
		Date d = getLastXDay(new Date(), NjdjConstants.MANBU_HIST_DAYS);
		param.put("beginDate", formats.format(d));
		List<SeTask> tl = seTaskService.listLastModel(param);
		
		for(int i = 1 ; i < NjdjConstants.MANBU_HIST_DAYS ; i ++){
			if(tl != null && tl.size() != 0){
				boolean alreadyFlag = false;
				for(SeTask seTask : tl){
					Date tDate = seTask.getQuerytime();
					Date date = getLastXDay(new Date(), i);
					if(tDate != null && formats.format(date).equals(formats.format(tDate)) ){
						System.out.println("已经获取"+formats.format(date));
						alreadyFlag = true;
					}
				}
				
				//如果未曾获取 则加入队列
				if(!alreadyFlag){
					Date date = getLastXDay(new Date(), i);
					Map<String, Object> task = new HashMap<String, Object>();
					task.put("querytime", formats.format(date));
					task.put("stime", formats.format(date)+"+0%3A0%3A0");
					task.put("etime", formats.format(date)+"+23%3A59%3A59");
					tasks.add(task);
				}
			} else {
				
				
				Map<String, Object> task = new HashMap<String, Object>();
				Date date = getLastXDay(new Date(), i);
				task.put("querytime", formats.format(date));
				task.put("stime", formatd.format(date)+"+0%3A0%3A0");
				task.put("etime", formatd.format(date)+"+23%3A59%3A59");
				tasks.add(task);
			}
		}
		
		
		return tasks;
	}
	
	//获取前若干天
	public static Date getLastXDay(Date date, int x) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, -x);
		date = calendar.getTime();
		return date;
	}
	
	
	
}
